#include <QGuiApplication>
#include <QDebug>

#include "Process.h"

Process::Process(QObject *parent) : QProcess(parent)
{
    setProcessChannelMode(QProcess::MergedChannels);
    connect(this, &QProcess::readyRead, this, &Process::onReadyRead);
    connect(this, &QProcess::stateChanged, this, &Process::onStateChanged);
    connect(this, qOverload<int, QProcess::ExitStatus>(&QProcess::finished), this, &Process::onFinished);
}

Process::~Process()
{
    if (state() != NotRunning) {
        terminate();
    }
}

void Process::start(const QString &program, const QVariantList &arguments)
{
    QStringList args;

    for (int i = 0; i < arguments.length(); i++) {
        args << arguments[i].toString();
    }

    qDebug() << "starting: " << program << args.join(" ");

    QProcess::start(program, args);
}

QString Process::applicationDirPath()
{
    return QGuiApplication::applicationDirPath();
}

bool Process::isRunning()
{
    return state() != NotRunning;
}

void Process::onReadyRead()
{
    const QString &text = QString(readAll());
    qDebug() << text;
    outputRead(text);
}

void Process::onFinished(int code, QProcess::ExitStatus /*status*/)
{
    finished(code);
}

void Process::onStateChanged(QProcess::ProcessState state)
{
    bool running = state == QProcess::Running;
    if (running != wasRunning) {
        wasRunning = running;
        emit isRunningChanged(running);
    }
}
